package com.guapi.controller;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.guapi.Application;
import com.guapi.dao.ResponseData;
import com.guapi.dao.User;
import com.guapi.exception.SelfException;
import com.guapi.security.UserDetailImpl;
import com.guapi.util.BaseConstant;
import com.guapi.util.ConversationConstant;
import com.guapi.util.KafkaConstant;
import com.guapi.util.RequestHelper;
import com.guapi.util.request.SelfRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author 瓜皮哦
 */

public abstract class BaseController<T> implements BaseConstant, KafkaConstant, ConversationConstant {

    protected ResponseData responseData = new ResponseData();

    @Value("${self.mail.register}")
    private String registerContent;

    @Value("${self.mail.reset}")
    private String resetContent;

    @Value("${self.web.site}")
    protected String website;

    @Value("${self.img.head.folder}")
    protected String headerFolder;

    @Value("${self.img.head.default}")
    protected String defaultHeader;

    protected static final String resourcePath = new File("src/main/resources/").getAbsolutePath();

    protected SelfRequest createRequest(HttpServletRequest request) {
        return RequestHelper.createServiceRequest(request);
    }

    protected void startPage(Map data) {
        if (!StrUtil.isEmptyIfStr(data.get("page")) && !StrUtil.isEmptyIfStr(data.get("limit"))) {
            PageHelper.startPage((Integer) data.get("page"), (Integer) data.get("limit"), true);
        }
    }

    protected static User getLoginUser() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth.getPrincipal() != null) {
            UserDetailImpl userDetail = (UserDetailImpl) auth.getPrincipal();
            return userDetail.getUser();
        } else {
            throw new SelfException("获取不到用户信息！请重新登录");
        }
    }

    protected String setMailArgs(String toMail, String captcha) {

        return getResource(registerContent)
                .replaceAll(BaseConstant.REPLACE_REGEX_MAIL, toMail)
                .replace(BaseConstant.REPLACE_CAPTCHA, captcha)
                .replace(BaseConstant.REPLACE_OURSITE, website);
    }

    protected String setForgetMail(String toMail, String ourSite) {
        return getResource(resetContent)
                .replaceAll(BaseConstant.REPLACE_REGEX_MAIL, toMail)
                .replace(BaseConstant.REPLACE_OURSITE, ourSite);
    }

    protected String getUserHeader(User loginUser) {
        return headerFolder + "user_" + loginUser.getId() + "_header";
    }

    protected String getResource(String name) {
        StringBuilder result = null;
        try {
            ClassLoader classLoader = Application.class.getClassLoader();
            URL resource = classLoader.getResource(name);
            System.out.println("路径是：" + resource.getPath());
            BufferedReader reader = new BufferedReader(new InputStreamReader(resource.openStream(), StandardCharsets.UTF_8));
            String line;
            result = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }
}
